package com.mtnz.njk.Service;

import cn.hutool.core.date.DateUtil;
import com.github.pagehelper.PageHelper;
import com.mtnz.njk.Mapper.*;
import com.mtnz.njk.Util.AdrCutUtil;
import com.mtnz.njk.Util.AdrCutVo;
import com.mtnz.njk.Util.ExcelUtils;
import com.mtnz.njk.Util.OrderStatus;
import com.mtnz.njk.entity.*;
import com.mtnz.njk.result.PageInfo;
import com.mtnz.njk.result.ResponseMessage;
import com.mtnz.njk.result.ResponseResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;

/**
 * @Description: 订单管理服务层
 * @Author: FBL
 * @CreateDate: 2019\8\21 0021 8:57
 * @Version: 1.0
 */
@Service
public class OrderManagerService {
    @Autowired
    OrderInfoMapper orderInfoMapper;

    @Autowired
    OrderProductMapper orderProductMapper;

    @Autowired
    BalanceOrderMapper balanceOrderMapper;

    @Autowired
    NjkUserMapper userMapper;

    @Autowired
    NjkUserServiceMapper userServiceMapper;

    @Autowired
    OrderManagerMapper orderManagerMapper;


    /**
     * 订单信息列表
     *
     * @param key
     * @param pageNum
     * @param pageSize
     * @return
     * @throws Exception
     */
    public ResponseResult listOrderInfo(String customerId, String serviceId, String orderStatus, String payMethod, String key, String beginTime, String endTime, Integer dealStatus, String orderInfoId, Integer pageNum, Integer pageSize) throws Exception {
        List<String> orderStatuses = null;
        if (orderStatus != null) {
            String[] split = orderStatus.split(",");
            orderStatuses = Arrays.asList(split);
        }
        ArrayList<String> userIds = new ArrayList<>();
        if (serviceId != null && !("").equals(serviceId)) {
            // 查询此客服的用户
            Example userExample = new Example(NjkUserEntity.class);
            userExample.createCriteria().andEqualTo("serviceId", serviceId);
            List<NjkUserEntity> njkUserEntities = userMapper.selectByExample(userExample);
            for (NjkUserEntity njkUserEntity : njkUserEntities) {
                userIds.add(njkUserEntity.getUserId());
            }
        }
        PageHelper.startPage(pageNum, pageSize);
        List<OrderInfoEntity> orderInfos = orderManagerMapper.getOrderInfos(customerId, userIds, orderStatuses, payMethod, key, beginTime, endTime);
        PageInfo<OrderInfoEntity> orderInfoEntityPageInfo = new PageInfo<>(orderInfos);
        // 分页后总订单信息
        List<OrderInfoEntity> orderInfoList = orderInfoEntityPageInfo.getList();

        // 查询所有订单商品信息
        List<OrderProductEntity> orderProductEntities = orderProductMapper.selectAll();
        // 查询所有余额充值的订单
        Example balanceOrderExample = new Example(BalanceOrderEntity.class);
        balanceOrderExample.createCriteria().andEqualTo("balanceStatus", 1);
        List<BalanceOrderEntity> balanceOrderEntities = balanceOrderMapper.selectByExample(balanceOrderExample);

        if (orderInfoList != null && orderInfoList.size() > 0) {
            for (OrderInfoEntity orderInfoEntity : orderInfoList) {
                ArrayList<OrderProductEntity> orderProducts = new ArrayList<>();
                for (OrderProductEntity orderProductEntity : orderProductEntities) {
                    if (orderInfoEntity.getOrderInfoId().equals(orderProductEntity.getOrderInfoId())) {
                        orderProducts.add(orderProductEntity);
                    }
                }
                // 将订单商品置入订单中
                orderInfoEntity.setProductEntities(orderProducts);
            }

            for (OrderInfoEntity orderInfoEntity : orderInfoList) {
                ArrayList<BalanceOrderEntity> balanceOrders = new ArrayList<>();
                for (BalanceOrderEntity balanceOrderEntity : balanceOrderEntities) {
                    if (orderInfoEntity.getOrderNumber().equals(balanceOrderEntity.getOrderName())) {
                        balanceOrders.add(balanceOrderEntity);
                    }
                }
                // 将余额充值订单置入其中
                orderInfoEntity.setBalanceOrders(balanceOrders);
            }

            // 将负责人姓名置入订单
            for (OrderInfoEntity orderInfoEntity : orderInfoList) {
                String userId = orderInfoEntity.getUserId();
                // 查询用户信息
                NjkUserEntity userEntity = userMapper.selectByPrimaryKey(userId);
                if (userEntity != null) {
                    // 查询客服信息
                    NjkUserServiceEntity njkUserServiceEntity = userServiceMapper.selectByPrimaryKey(userEntity.getServiceId());
                    if (njkUserServiceEntity != null) {
                        orderInfoEntity.setServiceName(njkUserServiceEntity.getName());
                    }
                }
            }
        }


        if (orderInfoId != null && !("").equals(orderInfoId) && dealStatus != null && !("").equals(dealStatus) && dealStatus == 1) {
            // 修改订单处理状态
            OrderInfoEntity orderInfoEntity = orderInfoMapper.selectByPrimaryKey(orderInfoId);
            orderInfoEntity.setDealStatus("1");
            orderInfoEntity.setOrderEndDateTime(DateUtil.now());
            orderInfoMapper.updateByPrimaryKeySelective(orderInfoEntity);
        }
        // 这个客服没有客户
        if (serviceId != null && !("").equals(serviceId) && (userIds == null || userIds.size() == 0)) {
            orderInfoEntityPageInfo.setPages(0);
            orderInfoEntityPageInfo.setTotal(0);
            orderInfoEntityPageInfo.setList(null);
        }
        return new ResponseResult(ResponseMessage.OK, orderInfoEntityPageInfo);
    }

    /**
     * 修改订单备注以及修改订单状态
     *
     * @param orderInfoId
     * @param orderExplain
     * @return
     * @throws Exception
     */
    public ResponseResult updateOrderRemark(String orderInfoId, String orderExplain, String orderStatus) throws Exception {
        OrderInfoEntity orderInfoEntity = new OrderInfoEntity();
        orderInfoEntity.setOrderInfoId(orderInfoId);
        if (orderExplain != null && !("").equals(orderExplain)) {
            orderInfoEntity.setOrderExplain(orderExplain);
        }
        if (orderStatus != null && !("").equals(orderStatus)) {
            orderInfoEntity.setOrderStatus(orderStatus);
        }
        int i = orderInfoMapper.updateByPrimaryKeySelective(orderInfoEntity);
        if (i > 0)
            return new ResponseResult(ResponseMessage.OK);
        return new ResponseResult(ResponseMessage.FAIL);
    }

    /**
     * 订单Excel导出
     *
     * @return
     * @throws Exception
     */
    public ResponseResult orderExcel(HttpServletResponse response, String beginTime, String endTime) throws Exception {
        //String[] str = {"订单号", "年份", "月份", "日期", "省份", "市区", "县城", "姓名", "电话", "货物", "规格", "数量", "单价", "折扣", "货款", "打款途径", "联系人", "备注", "发货时间","状态"};
        List<HashMap<String, Object>> mm = orderManagerMapper.orderExcel(beginTime, endTime);
        List<String[]> list = new ArrayList<>();
        for (int i = 0; i < mm.size(); i++) {
            String[] str = new String[20];
            str[0] = mm.get(i).get("orderNumber").toString();
            str[1] = mm.get(i).get("year").toString();
            str[2] = mm.get(i).get("month").toString();
            str[3] = mm.get(i).get("day").toString();
            String province = mm.get(i).get("province").toString();
            String city = mm.get(i).get("city").toString();
            String userAddress = mm.get(i).get("userAddress").toString();
            AdrCutVo adrCutVo = AdrCutUtil.addToObject(city);
            // 以前数据需要从中截取省市县，现在表中直接有省市县字段
            str[4] = adrCutVo.getProvince() == null ? province : adrCutVo.getProvince();
            str[5] = adrCutVo.getCity() == null ? city : adrCutVo.getCity();
            str[6] = adrCutVo.getCounty() == null ? userAddress : adrCutVo.getCounty();
            String NAME = mm.get(i).get("userName").toString();
            str[7] = NAME;
            str[8] = mm.get(i).get("userPhone").toString();
            str[9] = mm.get(i).get("productName").toString();
            str[10] = mm.get(i).get("productRemark").toString();
            str[11] = mm.get(i).get("number").toString();
            str[12] = mm.get(i).get("price").toString();
            str[13] = mm.get(i).get("subMoney") + "";
            str[14] = mm.get(i).get("realityMoney").toString();
            str[15] = mm.get(i).get("payMethod").toString();
            str[16] = mm.get(i).get("serviceName").toString();
            if (mm.get(i).get("orderExplain") != null) {
                str[17] = mm.get(i).get("orderExplain").toString();
            } else {
                str[17] = "";
            }
            str[18] = "";
            str[19] = OrderStatus.getOrderStatus(Integer.parseInt(mm.get(i).get("orderStatus").toString()));
            list.add(str);
        }

        String[] str = {"订单号", "年份", "月份", "日期", "省份", "市区", "县城", "姓名", "电话", "货物", "规格", "数量", "单价", "折扣", "货款", "打款途径", "联系人", "备注", "发货时间", "状态"};
        ExcelUtils.exportExelMerge(System.currentTimeMillis() + "_njk.xls", str, list, false, response, new Integer[]{0}, new Integer[]{0, 1, 2, 3, 4, 5, 6, 7, 8, 13, 14, 15, 16, 17, 18, 19}, new Integer[]{}, new Integer[]{});
        return new ResponseResult(ResponseMessage.OK);
    }

}
